package com.lty.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lty.common.BaseResponse;
import com.lty.common.DeleteRequest;
import com.lty.common.ErrorCode;
import com.lty.common.IdRequest;
import com.lty.common.PageRequest;
import com.lty.common.ResultUtils;
import com.lty.exception.BusinessException;
import com.lty.model.entity.TemplateInfo;
import com.lty.model.enums.StatusEnum;
import com.lty.service.impl.TemplateService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 模板表控制层
 * @author lty
 */
@Slf4j
@RestController
@RequestMapping("/template")
public class TemplateController {

    @Resource
    private TemplateService templateService;


    @ApiOperation(value = "添加")
    @PostMapping("/add")
    public BaseResponse<Long> addTemplate(@RequestBody TemplateInfo templateAddRequest) {
        if (templateAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        TemplateInfo template = new TemplateInfo();
        BeanUtils.copyProperties(templateAddRequest, template);
        boolean result = templateService.save(template);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return ResultUtils.success(template.getId());
    }


    @ApiOperation(value = "修改")
    @PostMapping("/update")
    public BaseResponse<Boolean> updateTemplate(@RequestBody TemplateInfo templateUpdateRequest) {
        if (templateUpdateRequest == null || templateUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        TemplateInfo template = new TemplateInfo();
        BeanUtils.copyProperties(templateUpdateRequest, template);
        TemplateInfo oldTemplate = templateService.getById(templateUpdateRequest.getId());
        if (oldTemplate == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        boolean result = templateService.updateById(template);
        return ResultUtils.success(result);
    }

    @ApiOperation(value = "通过id获取")
    @GetMapping(value = "/get/{id}")
    public BaseResponse<TemplateInfo> getByTemplateId(@PathVariable Long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        TemplateInfo template = templateService.getById(id);
        return ResultUtils.success(template);
    }

    @ApiOperation(value = "条件查询")
    @GetMapping(value = "/list")
    public BaseResponse<List<TemplateInfo>> listTemplate(TemplateInfo template) {
        List<TemplateInfo> templateList = templateService.getList();
        return ResultUtils.success(templateList);
    }

    @ApiOperation(value = "分页获取")
    @GetMapping(value = "/list/page")
    public BaseResponse<Page<TemplateInfo>> listTemplateByPage(PageRequest pageRequest, TemplateInfo template) {
        // 分页基本字段
        long current = pageRequest.getCurrent();
        long size = pageRequest.getPageSize();
        // 反爬虫
        if (size > 50) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询数量过多");
        }
        Page<TemplateInfo> page = new Page<>(current, size);
        Page<TemplateInfo> templatePage = templateService.page(page, templateService.buildQueryWrapper(template));
        return ResultUtils.success(templatePage);
    }

    @ApiOperation(value = "删除")
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTemplate(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        TemplateInfo oldTemplate = templateService.getById(id);
        if (oldTemplate == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        boolean b = templateService.removeById(id);
        return ResultUtils.success(b);
    }

    @ApiOperation(value = "备份文件")
    @PostMapping("/backup")
    public BaseResponse<Boolean> backupTemplate(@RequestBody IdRequest idRequest) {
        if (idRequest == null || idRequest.getIds().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = false;
        List<TemplateInfo> templateList = new ArrayList<>();
        for (Long id : idRequest.getIds()) {
            TemplateInfo oldTemplate = templateService.getById(id);
            if (oldTemplate != null) {
                oldTemplate.setStatus(StatusEnum.ADMIN.getValue());
                oldTemplate.setId(null);
                String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
                oldTemplate.setDescription(oldTemplate.getDescription() + "_backup_" + timestamp);
                templateList.add(oldTemplate);
            }
        }
        if (!templateList.isEmpty()) {
            b = templateService.saveBatch(templateList);
        }
        return ResultUtils.success(b);
    }
}
